var geocoder = null;
var map = null;
var bounds = null;
var jQT = null;

var deptMarkers = [];
var arrMarkers = [];

var addrType = null;

function initialize() {
    /*init geocoding service*/
    geocoder = new google.maps.Geocoder();

    /*Init gmap*/
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    /*bind btn evt for coding address*/
    $("#ity input[type=button]").bind("click", function(event) {
        processAddress(event);
    });

    jQT = new $.jQTouch({
    });

    $('#map_canvas').height($('#mapper').height() - 400);
    /*
     $('#map_canvas').height(
     $('#mapper').height() -
     $('#mapper .toolbar').outerHeight() -
     $('#marker-nav').outerHeight()
     );
     */
}

function fitsMarkersOnMap() {
    bounds = new google.maps.LatLngBounds();
    for (i in deptMarkers) {
        bounds.extend(deptMarkers[i].position);
    }
    for (i in arrMarkers) {
        bounds.extend(arrMarkers[i].position);
    }
    map.fitBounds(bounds);
}

function codeAddress(addr) {

    geocoder.geocode({ 'address': addr}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            var divId = null;

            /*select div for showing links*/
            if (addrType == 'dept') {
                divId = $('#ity_dept_show');
                deptMarkers = []
            } else {
                divId = $('#ity_arr_show');
                arrMarkers = [];
            }

            divId.empty();
            clearMarkers();

            var ul = $('<ul></ul>');

            for (var i = 0; i < results.length; i++) {
                /*salvo i markers per poterli togliere dalla mappa successivamnte*/
                var marker = addMarker(results[i].geometry.location, results[i].formatted_address);

                var link = $('<a></a>', {href:'#'}).append(marker.getTitle());
                link.data('marker', marker);

                link.bind('click', function(event) {
                    $('#mapper .toolbar')
                            .html(addrType == 'dept' ? '<h1>Departure</h1>' : '<h1>Arrival</h1>')
                            .click(function() {
								showScreen('ity');
							});
                    clearMarkers();
                    var marker = $(event.target).data('marker');
                    marker.setMap(map);
                    map.setCenter(marker.getPosition());
                    showScreen('mapper');
                });

                var li = $('<li></li>').append(link);
                ul.append(li);
            }
            $(divId).append(ul);

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });

}

/*search address, display marks on map*/
function processAddress(firedEvent) {
    var btName = $(firedEvent.target).attr("name");
    if (btName.indexOf("dept", 0) != -1) {
        addrType = "dept";
    } else if (btName.indexOf("arr", 0) != -1) {
        addrType = "arr";
    }

    var addressInput = $('input[type="text"][name$="' + btName.concat(":val") + '"]');

    codeAddress($(addressInput).val());
}

function activateMarker(marker) {
    var infowindow = new google.maps.InfoWindow({
        content: marker.getTitle()
    });
    infowindow.open(map, marker);
} // activateMarker

function addMarker(position, title) {
    // create a new marker to and display it on the map
    var marker = new google.maps.Marker({
        position: position,
        title: title,
        icon: 'img/pin-active.png'
    });

    // add the marker to the array of markers
    if (addrType == 'dept') {
        deptMarkers.push(marker);
    } else {
        arrMarkers.push(marker);
    }

    // capture touch click events for the created marker
    google.maps.event.addListener(marker, 'click', function() {
        // activate the clicked marker
        activateMarker(marker);
    });

    return marker;
} // addMarker

function clearMarkers() {
    var markers = null;
    if (addrType == 'dept') {
        markers = deptMarkers;
    } else {
        markers = arrMarkers;
    }

    for (var ii in markers) {
        markers[ii].setMap(null);
    } // for

} // clearMarkers

function getMarkerIndex(marker) {
    for (var ii = 0; ii < markers.length; ii++) {
        if (markers[ii] === marker) {
            return ii;
        } // if
    } // for

    return -1;
} // getMarkerIndex


function updateMarkerNav(markerIndex) {

    // find the marker nav element
    var markerNav = $('#marker-nav');

    // reset the disabled state for the images and unbind click events
    markerNav.find('img')
            .addClass('disabled')
            .unbind('click');

    // if we have more markers at the end of the array, then update
    // the marker state
    if (markerIndex < markers.length - 1) {
        markerNav.find('img.right')
                .removeClass('disabled')
                .click(function() {
            activateMarker(markers[markerIndex + 1]);
        });
    } // if

    if (markerIndex > 0) {
        markerNav.find('img.left')
                .removeClass('disabled')
                .click(function() {
            activateMarker(markers[markerIndex - 1]);
        });
    } // if
} // updateMarkerNav

function showScreen(screenId) {
    jQT.goTo('#' + screenId);
} // showScreen

function sortMarkers() {
    // sort the markers from top to bottom, left to right
    // remembering that latitudes are less the further south we go
    markers.sort(function(markerA, markerB) {
        // get the position of marker A and the position of marker B
        var posA = markerA.getPosition();
        var posB = markerB.getPosition();

        var result = posB.lat() - posA.lat();
        if (result === 0) {
            result = posA.lng() - posB.lng();
        } // if

        return result;
    });
} // sortMarkers